package com.go.where.family.api.utils.sms;

import java.net.URL;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.rpc.holders.LongHolder;
import javax.xml.rpc.holders.StringHolder;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.go.where.family.api.utils.sms.group.MobileListGroup;

/**
 * 短信部分
 */
public class SmsSend {

	private static Logger log = Logger.getLogger(SmsSend.class);

	private static long corpID; // 企业ID
	private static String loginName; // 登录帐号
	private static String password; // 密码，MD5(CorpID+帐号密码+TimeStamp)
	private static URL url;
	private static String timeStamp = ""; // 时间戳，MMDDHHMMSS（月日时分秒),如0514094912
	private static String addNum; // 扩展子号，附加于端口号后。
	private static String timer = "";// 定时时间：yyyy-MM-dd
	// HH:mm:ss 如:2010-05-14
	// 10:30:00
	private static long longSms = 0; // 是否以长短信方式发送,0-否；1-是
	private static MobileListGroup[] mobileList; // 接收号码列表，由MobileListGroup组成，为防止超时，每次提交短信，接收号码数量建议不要超过50个。
	private static StringHolder errMsg; // 错误信息，用于返回函数调用结果的文字描述
	private static ArrayOfSmsIDListHolder smsIDList; // 短信ID列表，用于返回发送成功的短信记录ID，此短信ID可用于状态报告匹配的识别。
	private static LongHolder count; // 调用函数的返回值：发送短信，返回短信ID(SmsID)

	public static MsmResultBean sendMsg(String mobiles, String content) {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmss");// 可以方便地修改日期格式
		timeStamp = dateFormat.format(now);
		log.info("时间戳，MMddHHmmss---" + timeStamp);

		// 初始化参数
		errMsg = new StringHolder();
		smsIDList = new ArrayOfSmsIDListHolder();
		count = new LongHolder();
		MsmResultBean msmBean = new MsmResultBean();

		// 获取帐号信息
		DataObjectBean bean = DataObjectFactory.getInstance();
		corpID = new Long(bean.getCordId());
		loginName = bean.getUserName();
		password = bean.getPasswd();
		// 获得实例化对象
		try {
			url = new URL(bean.getServerIP());
		} catch (Exception e) {
			log.error("", e);
		}
		MobsetApiSoap mobset = DataObjectFactory.getMobsetApi(url);
		// 将手机号码字符串分解到数组中
		String[] mobileArray = StringUtils.replace(mobiles, "；", ";")
				.split(";");
		mobileList = new MobileListGroup[mobileArray.length];

		for (int i = 0; i < mobileList.length; i++) {
			mobileList[i] = new MobileListGroup();
			mobileList[i].setMobile(mobileArray[i]);
		}

		// MD5密码加密
		MD5 md5 = new MD5();
		password = md5.getMD5ofStr(corpID + password + timeStamp);

		try {
			// 调用发送方法进行短信下发
			mobset.sms_Send(corpID, loginName, password, timeStamp, addNum,
					timer, longSms, mobileList, content, count, errMsg,
					smsIDList);
			log.info("发送的短信内容：" + content + ",手机号码：" + mobileList[0].getMobile());
			msmBean.setErrMsg(errMsg);
			msmBean.setMobileList(mobileList);
			msmBean.setSmsIDList(smsIDList);

		} catch (RemoteException e) {
			log.error("短信发送异常", e);
		}
		return msmBean;
	}
}
